package com.neusoft.elmboot.controller;

import java.util.ArrayList;
import java.util.List;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.neusoft.elmboot.po.*;
import com.neusoft.elmboot.po.vo.BusinessOrderVO;
import com.neusoft.elmboot.service.*;
import com.neusoft.elmboot.service.BusinessWalletService;
import com.neusoft.elmboot.util.CommonUtil;
import com.neusoft.elmboot.util.response.ResultBody;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;

@RestController
@RequestMapping("/elm/OrdersController")
public class OrdersController {

	@Autowired
	private OrdersService ordersService;

	//@Autowired
	//private UserService userService;

	@Autowired
	private BusinessService businessService;

	//@Autowired
	//private FoodService foodService;

	@Autowired
	private DeliveryAddressService deliveryAddressService;
	
	// @Autowired
	// private WalletService walletService; // 已替换为 BusinessWalletService
	
	@Autowired
	private PointsService pointsService;
	
	@Autowired
	private BusinessWalletService businessWalletService;
	
	//@Autowired
	//private UserCouponService userCouponService;

	@RequestMapping("/createOrders")
	public ResultBody createOrders(Orders orders) throws Exception {
		try {
			// 验证必填参数
			if (orders.getUserId() == null || orders.getBusinessId() == null) {
				return ResultBody.error("用户ID或商家ID不能为空！", -1);
			}
			if (orders.getDaId() == null) {
				return ResultBody.error("请选择收货地址！", -1);
			}
			if (orders.getOrderTotal() == null || orders.getOrderTotal() <= 0) {
				return ResultBody.error("订单金额异常！", -1);
			}
			
			orders.setOrderDate(CommonUtil.getCurrentDate());
			int orderId = ordersService.createOrders(orders);
			return ResultBody.success("添加订单成功！", orderId);
		} catch (Exception e) {
			e.printStackTrace();
			return ResultBody.error("添加订单失败：" + e.getMessage(), -1);
		}
	}
	
	/**
	 * 用户申请退款：仅已支付订单可申请，设置 refundStatus=1 并记录原因
	 */
	@RequestMapping("/applyRefund")
	public ResultBody applyRefund(@RequestParam Integer orderId,
	                             @RequestParam(required = false, name = "refundReason") String refundReason) throws Exception {
		try {
			Orders orders = ordersService.getOrdersById(orderId);
			if (orders == null) {
				return ResultBody.error("订单不存在", null);
			}
			// 仅已支付订单可申请退款
			if (orders.getOrderState() == null || orders.getOrderState() != 1) {
				return ResultBody.error("仅已支付订单可以申请退款", null);
			}
			// 如果已经有退款状态（非0），不允许重复申请
			if (orders.getRefundStatus() != null && orders.getRefundStatus() != 0) {
				return ResultBody.error("该订单已提交过退款申请", null);
			}
			ordersService.updateRefundInfo(orderId, 1, refundReason);
			return ResultBody.success("退款申请已提交，等待商家处理", null);
		} catch (Exception e) {
			e.printStackTrace();
			return ResultBody.error("提交退款申请失败：" + e.getMessage(), null);
		}
	}
	
	@RequestMapping("/getOrdersById")
	public ResultBody getOrdersById(@RequestParam Integer orderId) throws Exception{
		try {
			Orders orders = ordersService.getOrdersById(orderId);
			if (orders == null) {
				return ResultBody.error("不存在此订单！", null);
			}

			// 获取地址，如果为空则使用默认值
			String address = "";
			DeliveryAddress deliveryAddress = deliveryAddressService.getDeliveryAddressById(orders.getDaId());
			if (deliveryAddress != null) {
				address = deliveryAddress.getAddress();
			}
			
			Business business = businessService.getBusinessById(orders.getBusinessId());
			if (business == null) {
				return ResultBody.error("商家信息不存在！", null);
			}
			
			List<OrderDetailet> detailets = ordersService.getOrderDetailetByOrderId(orders.getOrderId());
			List<BusinessOrderVO> businessOrderVOList = new ArrayList<>();

			JSONObject object = new JSONObject();

			for (OrderDetailet detailet : detailets) {
				BusinessOrderVO businessOrderVO = BusinessOrderVO.builder()
						.foodName(detailet.getFoodName())
						.foodPrice(detailet.getFoodPrice())
						.quantity(detailet.getQuantity()).build();
				businessOrderVOList.add(businessOrderVO);
			}

			object.putOpt("orderId", orders.getOrderId());
			object.putOpt("orderDate", orders.getOrderDate());
			object.putOpt("address", address);
			object.putOpt("businessName", business.getBusinessName());
			object.putOpt("businessAddress", business.getBusinessAddress());
			// 原始总价（未打折）
			object.putOpt("originalTotal", orders.getOrderTotal());
			// 实付金额：优先使用 finalTotal，如果为空则回退到原始总价
			Double detailFinalTotal = orders.getFinalTotal() != null ? orders.getFinalTotal() : orders.getOrderTotal();
			object.putOpt("finalTotal", detailFinalTotal);
			// totalPrice 作为前端展示用金额，统一映射到实付金额
			object.putOpt("totalPrice", detailFinalTotal);
			object.putOpt("discountAmount", orders.getDiscountAmount());
			object.putOpt("couponDiscountAmount", orders.getCouponDiscountAmount());
			object.putOpt("levelDiscountAmount", orders.getLevelDiscountAmount());
			object.putOpt("deliveryPrice", business.getDeliveryPrice());
			object.putOpt("orderState", orders.getOrderState());
			object.putOpt("refundStatus", orders.getRefundStatus());
			object.putOpt("refundReason", orders.getRefundReason());
			object.putOpt("priceDetails", businessOrderVOList);

			return ResultBody.success("获取订单信息成功！", object);
		} catch (Exception e) {
			e.printStackTrace();
			return ResultBody.error("获取订单信息失败！", null);
		}
	}
	
	@RequestMapping("/listOrdersByUserId")
	public ResultBody listOrdersByUserId(@RequestParam String userId) throws Exception{
		try {
			List<Orders> ordersList = ordersService.listOrdersByUserId(userId);
			if (ordersList.isEmpty()) {
				return ResultBody.success("获取成功！", new JSONArray());
			}
			JSONArray re = new JSONArray();
			for (Orders orders : ordersList) {
				try {
					// 获取配送地址
					String address = "";
					if (orders.getDaId() != null) {
						DeliveryAddress da = deliveryAddressService.getDeliveryAddressById(orders.getDaId());
						if (da != null) {
							address = da.getAddress();
						}
					}
					
					// 获取商家信息
					Business business = businessService.getBusinessById(orders.getBusinessId());
					if (business == null) {
						continue;
					}
					
					// 获取订单详情
					List<OrderDetailet> detailets = ordersService.getOrderDetailetByOrderId(orders.getOrderId());
					List<BusinessOrderVO> businessOrderVOList = new ArrayList<>();

					if (detailets != null && !detailets.isEmpty()) {
						for (OrderDetailet detailet : detailets) {
							BusinessOrderVO businessOrderVO = BusinessOrderVO.builder()
									.foodName(detailet.getFoodName())
									.foodPrice(detailet.getFoodPrice())
									.quantity(detailet.getQuantity()).build();
							businessOrderVOList.add(businessOrderVO);
						}
					}

					JSONObject object = new JSONObject();
					object.putOpt("orderId", orders.getOrderId());
					object.putOpt("tel", orders.getUserId());
					object.putOpt("address", address);
					object.putOpt("businessName", business.getBusinessName());
					object.putOpt("businessAddress", business.getBusinessAddress());
					// 原始总价（未打折）
					object.putOpt("originalTotal", orders.getOrderTotal());
					// 实付金额：优先使用 finalTotal，如果为空则回退到原始总价
					Double finalTotal = orders.getFinalTotal() != null ? orders.getFinalTotal() : orders.getOrderTotal();
					object.putOpt("finalTotal", finalTotal);
					// totalPrice 作为前端展示用金额，统一映射到实付金额
					object.putOpt("totalPrice", finalTotal);
					object.putOpt("deliveryPrice", business.getDeliveryPrice());
					object.putOpt("priceDetails", businessOrderVOList);
					object.putOpt("orderState", orders.getOrderState());
					object.putOpt("refundStatus", orders.getRefundStatus());
					object.putOpt("refundReason", orders.getRefundReason());

					re.add(object);
				} catch (Exception orderException) {
					// 单个订单处理失败，继续处理下一个
					orderException.printStackTrace();
				}
			}

			return ResultBody.success("获取成功！", re);
		} catch (Exception e) {
			e.printStackTrace();
			return ResultBody.error("获取失败！", null);
		}
	}

	@RequestMapping("/payment")
	public ResultBody updateOrderState(@RequestParam Integer state,
					   @RequestParam Integer orderId,
					   @RequestParam(required = false) String paymentType,
					   @RequestParam(required = false) String payPwd) throws Exception{
		try {
			// 如果使用钱包支付
			if ("wallet".equals(paymentType) && payPwd != null) {
				Orders orders = ordersService.getOrdersById(orderId);
				if (orders == null) {
					return ResultBody.error("订单不存在", null);
				}
				String userId = orders.getUserId();
				String businessId = orders.getBusinessId();
				// 使用实际支付金额 finalTotal 进行扣费；如果为空则回退到原始总价
				Double paidAmount = orders.getFinalTotal() != null ? orders.getFinalTotal() : orders.getOrderTotal();
				
				// 使用商家钱包服务处理支付（包含平台手续费逻辑）
				BigDecimal amount = BigDecimal.valueOf(paidAmount);
				String transId = businessWalletService.processOrderPayment(userId, businessId, orderId, amount, payPwd);
				// 支付成功后更新订单状态并记录支付方式
				ordersService.updateOrderStateWithPaymentType(state, paymentType, orderId);
				
				// 添加积分和经验值，基于实付金额
				try {
					pointsService.addPointsFromPayment(userId, paidAmount);
				} catch (Exception e) {
					// 积分添加失败不影响支付成功
					e.printStackTrace();
				}
				return ResultBody.success("钱包支付成功", transId);
			} else {
				// 其他支付方式（支付宝、微信等）
				Orders orders = ordersService.getOrdersById(orderId);
				if (orders == null) {
					return ResultBody.error("订单不存在", null);
				}
				// 更新订单状态并记录支付方式（如果提供）
				if (paymentType != null && !paymentType.isEmpty()) {
					ordersService.updateOrderStateWithPaymentType(state, paymentType, orderId);
				} else {
					ordersService.updateOrderState(state, orderId);
				}
				
				// 添加积分和经验值，基于实付金额
				Double paidAmount = orders.getFinalTotal() != null ? orders.getFinalTotal() : orders.getOrderTotal();
				try {
					pointsService.addPointsFromPayment(orders.getUserId(), paidAmount);
				} catch (Exception e) {
					// 积分添加失败不影响支付成功
					e.printStackTrace();
				}
				return ResultBody.success("支付成功", null);
			}
		} catch (Exception e) {
			e.printStackTrace();
			return ResultBody.error("支付失败：" + e.getMessage(), null);
		}
	}
	
	@RequestMapping("/user/cancelOrder")
	public ResultBody cancelOrder(@RequestParam Integer orderId) throws Exception{
		try {
			Orders orders = ordersService.getOrdersById(orderId);
			if (orders.getOrderState() == 0) {
				ordersService.cancelOrder(orderId);
				return ResultBody.success("订单已取消！", null);
			} else if (orders.getOrderState() == 1) {
				return ResultBody.error("已支付的订单不能直接取消，请联系商家！", null);
			}
			return ResultBody.error("不知道", null);
		} catch (Exception e) {
			return ResultBody.error("订单取消失败！", null);
		}
	}
	
	/**
	 * 使用优惠券创建订单
	 */
	@RequestMapping("/createOrdersWithCoupon")
	public ResultBody createOrdersWithCoupon(Orders orders, @RequestParam(required = false) Integer couponId) throws Exception {
		try {
			// 验证必填参数
			if (orders.getUserId() == null || orders.getBusinessId() == null) {
				return ResultBody.error("用户ID或商家ID不能为空！", -1);
			}
			if (orders.getDaId() == null) {
				return ResultBody.error("请选择收货地址！", -1);
			}
			if (orders.getOrderTotal() == null || orders.getOrderTotal() <= 0) {
				return ResultBody.error("订单金额异常！", -1);
			}
			
			orders.setOrderDate(CommonUtil.getCurrentDate());
			int orderId = ordersService.createOrdersWithCoupon(orders, couponId);
			return ResultBody.success("添加订单成功！", orderId);
		} catch (Exception e) {
			e.printStackTrace();
			return ResultBody.error("添加订单失败：" + e.getMessage(), -1);
		}
	}
}
